package com.tomagency.cyberlab.client;

import com.tomagency.cyberlab.client.place.ObjectListenPlace;
import com.tomagency.cyberlab.client.place.ScanAppPlace;
import com.tomagency.cyberlab.client.rpc.BelegService;
import com.tomagency.cyberlab.client.rpc.BelegServiceAsync;
import com.tomagency.cyberlab.client.rpc.ScannerService;
import com.tomagency.cyberlab.client.rpc.ScannerServiceAsync;
import com.tomagency.cyberlab.client.rpc.UserService;
import com.tomagency.cyberlab.client.rpc.UserServiceAsync;
import com.tomagency.cyberlab.client.ui.ObjectListenView;
import com.tomagency.cyberlab.client.ui.ObjectListenViewImpl;
import com.tomagency.cyberlab.shared.*;
import com.tomagency.cyberlab.shared.rpc.GammalibRequestFactory;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ScrollEvent;
import com.google.gwt.user.client.Window.ScrollHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;


import de.gammadata.gwt.proxy.KontaktListProxy;

import com.tomagency.cyberlab.client.events.WindowScrollEvent;
import com.tomagency.cyberlab.client.mapper.*;

import java.util.*;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Cyberlab implements EntryPoint {
	



	
	private  RpcServiceProvider serviceProvider;
	private Place defaultPlace = new ObjectListenPlace(ObjectListenPlace.BELEGLISTE);
	private SimplePanel appWidget = new SimplePanel();
		

	ClientFactory clientFactory;
	
	HorizontalPanel loginPanel = new HorizontalPanel();
	final Label msg=new Label();
	
	int lastScrollTop=0;
	int lastScrollLeft=0;
	final HTML scrollLabel=new HTML();


	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		// Create ClientFactory using deferred binding so we can replace with different
		// impls in gwt.xml
//		ClientFactory clientFactory = GWT.create(ClientFactory.class);
		clientFactory = new ClientFactoryImpl();
		serviceProvider = clientFactory.getRpcServiceProvider();
		EventBus eventBus = clientFactory.getEventBus();
		PlaceController placeController = clientFactory.getPlaceController();
		
		// Start ActivityManager for the main widget with our ActivityMapper
		ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
		ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
		activityManager.setDisplay(appWidget);
		
		// Start PlaceHistoryHandler with our PlaceHistoryMapper
		AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
		PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
		historyHandler.register(placeController, eventBus, defaultPlace);

		loginPanel = new HorizontalPanel();
		
		final TextBox userName = new TextBox();
		userName.setText("username");
		loginPanel.add(userName);
		
		final PasswordTextBox password = new PasswordTextBox();
		password.setText("passwort");
		loginPanel.add(password);
		
		final Button sendButton = new Button("Login");
		loginPanel.add(sendButton);
		
		
		
		final Label errorLabel = new Label();
		sendButton.addStyleName("sendButton");
		
		RootPanel.get("login").add(loginPanel);
		RootPanel.get("loginerror").add(msg);
		
		serviceProvider.getRequestFactory().initialize(eventBus);

		
		userName.setFocus(true);
		userName.selectAll();
				

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				doLogin(userName.getText(),password.getText());
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					doLogin(userName.getText(),password.getText());
				}
			}
		}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */


		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
	    sendButton.addClickHandler(handler);
		password.addKeyUpHandler(handler);
		
		
		/*
		 * Window Scrollbehandlung
		 */
		
		RootPanel.get("scrollinfo").add(scrollLabel);
		lastScrollTop = Window.getScrollTop();
		lastScrollLeft = Window.getScrollLeft();
		Window.addWindowScrollHandler(new ScrollHandler(){

			@Override
			public void onWindowScroll(ScrollEvent event) {	
				boolean down = lastScrollTop<event.getScrollTop();
				boolean right = lastScrollLeft<Window.getScrollLeft();
				//Testeinschub für Windowscroll Listener
				/*
				StringBuilder html =new StringBuilder();
				html.append("height: "+Window.getClientHeight()+ " width: "+Window.getClientWidth()
				+"<br/>"+"top: "+event.getScrollTop()+ " lastTop:"+lastScrollTop +" down: "+down
				+"<br/>"+"left: "+event.getScrollLeft()+ " lastLeft:"+lastScrollLeft +" right: "+right
			

				+"<br/>appcontainer height: "+RootPanel.get("appcontainer").getOffsetHeight()
				+"<br/>appcontainer el.height: "+RootPanel.get("appcontainer").getElement().getAbsoluteBottom()

				);
				scrollLabel.setHTML(html.toString());
				*/
				WindowScrollEvent wse = new WindowScrollEvent();
				wse.setClientHeight(Window.getClientHeight());
				wse.setClientWidth(Window.getClientWidth());
				wse.setTopPosition(event.getScrollTop());
				wse.setLeftPosition(Window.getScrollLeft());				
				wse.setScrollDown(down);
				wse.setScrollRight(right);
				
				
				clientFactory.getEventBus().fireEvent(wse);
				
				lastScrollTop = event.getScrollTop();
				lastScrollLeft = Window.getScrollLeft();
			}
		});

	}
	
//	Button belegAppButton;
	Button userAppButton;
	Button belegAppNeuButton;
	Button messageAppButton;
	Button scanAppButton;
	
	private void buildNavigation(){
		
		belegAppNeuButton = new Button();
		belegAppNeuButton.addStyleName(CssGlobalStyleNames.NAVI_BUTTON);
		belegAppNeuButton.setText("Belegliste");
		belegAppNeuButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				goTo(new ObjectListenPlace(ObjectListenPlace.BELEGLISTE));
				
			}});
		
		userAppButton = new Button();
		userAppButton.addStyleName(CssGlobalStyleNames.NAVI_BUTTON);
		userAppButton.setText("Kontaktliste");
		userAppButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {				
				goTo(new ObjectListenPlace(ObjectListenPlace.KONTAKTLISTE));
				
			}});
		
		messageAppButton = new Button();
		messageAppButton.addStyleName(CssGlobalStyleNames.NAVI_BUTTON);
		messageAppButton.setText("Postings");
		messageAppButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				goTo(new ObjectListenPlace(ObjectListenPlace.POSTINGLISTE));
				
			}});
		

		
		scanAppButton = new Button();
		scanAppButton.addStyleName(CssGlobalStyleNames.NAVI_BUTTON);
		scanAppButton.setText("Taopix-Scanstatus");
		scanAppButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				goTo(new ScanAppPlace("scanapp"));
				
				
			}});
		

		
		VerticalPanel vp = new VerticalPanel();
		vp.add(belegAppNeuButton);
		vp.add(userAppButton);
		vp.add(messageAppButton);
		vp.add(scanAppButton);
		RootPanel.get("navigation").add(vp);
	}
	
	/**
	 * Navigate to a new Place in the browser
	 */
	private void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}
		
	
	
	
	
	private void doLogin(String username, String pw){
		
		serviceProvider.getUserService().doLogin(username, pw, (new AsyncCallback<LoginResult>(){

			@Override
			public void onFailure(Throwable caught) {
			msg.setText("fehler beim login: "+caught.getMessage());
				
			}

			@Override
			public void onSuccess(LoginResult result) {
				if (result.isValidUser()){
					loginPanel.clear();
					loginPanel.add(new HTML(result.getMessage()));
					buildNavigation();
					RootPanel.get("appcontainer").add(appWidget);					
					msg.setText("");
					//Default Start-Place aufrufen
					goTo(defaultPlace);
					
				}
				else{
					msg.setText(result.getMessage());
				}
				
			}
			
		}));
		
	}
	
}
